package com.sqfw.project.utils;

import com.sqfw.common.constant.HttpStatus;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 对称加解密工具类
 *
 * @author jiangw15@chinatelecom.cn
 *
 */
public class AESUtils {

    // 手机号加密统一的秘钥
    public static final String CELLPHONE_KEY = "CELLPHONE";

    private static final String SYN_KEY = "SYN_KEY";

    // 编码方式
    public static final String charset = "UTF-8";

    /**
     * 加密
     *
     * @param source
     * @param key
     * @return
     */
    public static String encrypt(String source, String key) {
        try {
            key = MD5Utils.encrypt16(key);
            IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes(charset));
            SecretKeySpec sks = new SecretKeySpec(key.getBytes(charset), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, sks, zeroIv);
            byte[] encryptedData = cipher.doFinal(source.getBytes(charset));
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 解密
     *
     * @param encrypted
     * @param key
     * @return
     */
    public static String decrypt(String encrypted, String key) {
        try {
            key = MD5Utils.encrypt16(key);
            byte[] byteMi = Base64.getDecoder().decode(encrypted);
            IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes(charset));
            SecretKeySpec sks = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, sks, zeroIv);
            byte[] decryptedData = cipher.doFinal(byteMi);
            return new String(decryptedData, charset);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
//        String str = encrypt("17521358420", "CALLBACK_ORDER_KEY");
//        System.out.println(str);
//        String str2 = decrypt(str, "CALLBACK_ORDER_KEY");
//        System.out.println(str2);
//        String str1 = decrypt(str, CELLPHONE_KEY);
//        System.out.println(str1);
//        String a = null;
//        String b = "b";
//
//        if (b.equals(a)) {
//
//        }
        System.out.println("杀杀杀水水水水水水水水水水水水水水杀杀杀杀杀杀杀杀杀杀杀杀杀杀杀水水水水水水水水水水水水水水水水".length());



    }
}
